﻿using Permissions;
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
using System.Management;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using HalconDotNet;
using Halcon二次开发.Tools;
using System.Windows.Shapes;
namespace Halcon二次开发.View.应用_加载框
{
    public partial class LoadForm : Form
    {
        ComputerInfor computerInfor;
        public LoadForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 窗体加载方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadForm_Load(object sender, EventArgs e)
        {
            //获取序列号生成序列号
            computerInfor = new ComputerInfor();
            byte[] key = Encoding.UTF8.GetBytes("nbsd1234");
            byte[] iv = Encoding.UTF8.GetBytes("ioio4444");

            if (!File.Exists("ben.config"))
            {
                File.Create("ben.config").Close();
            }
            string str1 = File.ReadAllText("ben.config");
            if (str1.Length > 0)
            {
                // 解密
                byte[] decrypted = computerInfor.Decrypt(computerInfor.StringToByteArray(str1), key, iv);
                DateTime oldTime;
                if (DateTime.TryParse(Encoding.UTF8.GetString(decrypted), out oldTime))
                {
                    if (DateTime.Now < oldTime)
                    {
                        //不在授权时间内
                        DialogResult result = MessageBox.Show("该计算机已经超过使用时间无法启动软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        if (result == DialogResult.OK)
                        {
                            this.Close();
                        }
                    }
                }
                else
                {
                    //不在授权时间内
                    DialogResult result = MessageBox.Show("该计算机已经超过使用时间无法启动软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    if (result == DialogResult.OK)
                    {
                        this.Close();
                    }
                }
            }
            else
            {
                //不在授权时间内
                DialogResult result = MessageBox.Show("该计算机已经超过使用时间无法启动软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                if (result == DialogResult.OK)
                {
                    this.Close();
                    return;
                }
            }

            //获取CPU信息
            string query = "SELECT * FROM Win32_Processor";
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    computerInfor.Name = obj["Name"] + "";
                    computerInfor.Description = obj["Description"] + "";
                    computerInfor.Manufacturer = obj["Manufacturer"] + "";
                    computerInfor.ProcessorId = obj["ProcessorId"] + "";   //BFEBFBFF00090672
                    computerInfor.NumberOfCores = obj["NumberOfCores"] + "";
                    computerInfor.NumberOfLogicalProcessors = obj["NumberOfLogicalProcessors"] + "";
                }
            }
            //获取序列号
            string query3 = "SELECT * FROM Win32_ComputerSystemProduct";
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query3))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    computerInfor.UUID = obj["UUID"] + "";   //8DB7A800-D3BC-11EE-8351-88E8679D1200
                }
            }
            // 启动文件加密
            byte[] encrypted = computerInfor.Encrypt(Encoding.UTF8.GetBytes(computerInfor.GetInfor()), key, iv);

            //生成lincese文件
            File.WriteAllText("App.lincese", computerInfor.ByteArrayToString(encrypted));

            bool OpenCheck = false;
            if (File.Exists("initiate.config"))
            {
                //有文件
                string value = File.ReadAllText("initiate.config");
                if (computerInfor.ComputeSHA256() == value)
                {
                    //通过启动文件校验了,还要进行时间判定
                    if (File.Exists("initiate.xml"))
                    {
                        byte[] time = computerInfor.Decrypt(computerInfor.StringToByteArray(File.ReadAllText("initiate.xml")), key, iv);
                        string str = Encoding.UTF8.GetString(time);
                        if (str.Contains("至"))
                        {
                            DateTime stratTime = DateTime.Parse(str.Substring(0, str.IndexOf("至")));
                            DateTime endTime = DateTime.Parse(str.Substring(str.IndexOf("至") + 1));

                            if (DateTime.Now > stratTime && DateTime.Now < endTime)
                            {
                                //在设置的时间内
                                OpenCheck = true;
                            }
                            else
                            {
                                //不在授权时间内
                                DialogResult result = MessageBox.Show("该计算机已经超过使用时间无法启动软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                if (result == DialogResult.OK)
                                {
                                    this.Close();
                                }
                            }
                        }
                        else
                        {
                            //不在授权时间内
                            DialogResult result = MessageBox.Show("该计算机已经超过使用时间无法启动软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            if (result == DialogResult.OK)
                            {
                                this.Close();
                            }
                        }
                    }
                    else
                    {
                        //不在授权时间内
                        DialogResult result = MessageBox.Show("该计算机已经超过使用时间无法启动软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        if (result == DialogResult.OK)
                        {
                            this.Close();
                        }
                    }

                }
            }
            if (OpenCheck)
            {
                //校验成功才可进入程序
                CheckForIllegalCrossThreadCalls = false;
                using (BackgroundWorker bw = new BackgroundWorker())
                {
                    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);//开始的事件

                    bw.DoWork += new DoWorkEventHandler(bw_DoWork);//完成的事件

                    bw.RunWorkerAsync("Tank");
                }
            }
            else {
                DialogResult result = MessageBox.Show("该计算机无法获得授权使用,请联系管理员获得密钥!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                if (result == DialogResult.OK)
                {
                    //关闭程序
                    this.Close();
                }
            }
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0;i<100;i++) {
                Thread.Sleep(10);//延时

                this.progressBar1.Value = i;

                this.progressBar1.Text = i.ToString() + "%";
            }
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)//后台线程完成后的响应事件
        {
            Form1 form = new Form1(this);   
            form.Show();

            this.Hide();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void LoadForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            byte[] key = Encoding.UTF8.GetBytes("nbsd1234");
            byte[] iv = Encoding.UTF8.GetBytes("ioio4444");

            //启动文件加密
            byte[] encrypted = computerInfor.Encrypt(Encoding.UTF8.GetBytes(DateTime.Now.ToString("F")), key, iv);

            //生成lincese文件
            File.WriteAllText("ben.config", computerInfor.ByteArrayToString(encrypted));
        }
    }
}
